<script setup lang="ts">
import {ref, toRefs} from "vue";

const emits = defineEmits<{
  (e: "ok"): void;
  (e: "cancel"): void;
  (e: "beforeOk", callback: (bool: boolean) => void ): void;
}>();

const props = withDefaults(
  defineProps<{
    title: string;
    width?: number;
    mask?: boolean;
    maskClosable?: boolean;
    footer?: boolean;
    okText?: string;
    cancelText?: string;
    isBeforeOk?: boolean;
    loading?: boolean
  }>(),
  {
    width: 700,
    mask: true,
    maskClosable: true,
    footer: true,
    okText: "确定",
    cancelText: "取消",
    isBeforeOk: true,
    loading: false
  }
);

const { loading } = toRefs(props);

const show = ref<boolean>(false);

const init = () => {
  show.value = true;
  loading.value = false;
};

const close = () => {
  show.value = false;
};

const handleOk = () => {
  emits("ok");
};

const handleSubmit = (done: (closed: boolean) => void):void | boolean | Promise<void | boolean> => {
  if (props.isBeforeOk) {
    emits("beforeOk",  ((bool: boolean) => {
      loading.value = bool;
      done(bool);
    }));
  } else {
    done(true);
  }

};

const handleCancel = () => {
  emits("cancel");
};

defineExpose({
  init,
  close,
});
</script>

<template>
  <a-drawer
    :visible="show"
    :width="width"
    :title="title"
    :mask="mask"
    :mask-closable="maskClosable"
    :footer="footer"
    @ok="handleOk"
    @cancel="handleCancel"
    @before-ok="handleSubmit"
    :ok-text="okText"
    :cancel-text="cancelText"
    :ok-loading="loading"
  >
    <slot></slot>

    <!-- <template #footer>
    </template> -->
  </a-drawer>
</template>

<style scoped lang="scss">
</style>